# -*- coding: utf-8 -*-

"""
* Copyright (C) 2016 GridSafe, Inc.
"""
from django.http.response import HttpResponseRedirect
from django.shortcuts import render
from django.http import JsonResponse

from apps.wallet.models.community import Share
from apps.wallet.forms import ShareForm


def addShare(request):
    """添加"""
    context = {}
    user = request.user
    if request.method == 'POST':
        form = ShareForm(request.POST)
        if form.is_valid():
            f = form.save(commit=False)
            f.user = user.id
            f.save()
            return HttpResponseRedirect('/manage/share/list/')
        context['form'] = form
    else:
        form = ShareForm()
        context['form'] = form
    return render(request, 'share/add.html', context)


def delShare(request):
    if request.method == 'POST':
        id = request.POST.get('id')
        Share.objects.filter(id=id).delete()
        return JsonResponse({
            'status': 'success',
            'message': '删除成功'
        })


def sharelist(request):
    """个人分享列表."""
    context = {}
    user = request.user

    title = request.GET.get('title', '')
    share = Share.objects.filter(user=user.id)
    if title:
        share = share.filter(title__contains=title)

    context['share'] = share
    return render(request, 'share/list.html', context)
